package aspirecn.project3.controller;

import aspirecn.project3.mapper.GoodsDetailMapper;
import aspirecn.project3.model.DetailPicAdress;
import aspirecn.project3.model.GoodsDetail;
import aspirecn.project3.model.dto.GoodsAndPics;
import aspirecn.project3.model.dto.IdList;
import aspirecn.project3.service.GoodService;
import aspirecn.project3.util.JsonData;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author czl
 * **/
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodService goodsService;

    @Autowired
    private GoodsDetailMapper goodsDetailMapper;

    /**
     * 分页查询
     * **/
    @GetMapping("/list/pages")
    public JsonData getGoodsPages(@RequestParam("page") int page,
                                  @RequestParam("limit") int limit, @RequestParam("keyWord") String keyWord) throws JSONException {

        List<GoodsDetail> goodsList = null;
        try{
            goodsList = goodsService.getGoodsByPage((page-1)*limit, limit, keyWord);
        }catch(Exception e){

            return JsonData.buildError("查询失败");
        }


        return JsonData.buildSuccess(goodsList);
    }

    /**
     * 添加商品信息
     * **/
    @PostMapping("/save")
    public JsonData save(GoodsAndPics goodsAndPics) throws JSONException {

        try{
            GoodsDetail goods = new GoodsDetail(goodsAndPics.getTITLE(), goodsAndPics.getSUBTITLE(), goodsAndPics.getDETAIL(),
                    goodsAndPics.getPOINT(), goodsAndPics.getFirstPictureAddress(), goodsAndPics.getFirstDirectory(), goodsAndPics.getSecondDirectory(),
                    goodsAndPics.getClinkCount(), goodsAndPics.getClinkTime(), goodsAndPics.getListingTime(), goodsAndPics.getUpdateTime(), goodsAndPics.getGoodsStates(), goodsAndPics.getGoodsSort());

            goodsService.addGoods(goods);


            List<String> pics = goodsAndPics.getPics();
            Long id = goodsAndPics.getGoodId();
            for (int i = 0; i < pics.size(); i++) {
                DetailPicAdress adress = new DetailPicAdress(id, pics.get(i));
                goodsService.addGoodsPics(adress);
            }
        }catch(Exception e){

            return JsonData.buildError("添加失败");
        }

        return JsonData.buildSuccess("添加成功");
    }

    /**
     * 通过商品id删除商品
     * **/
    @PostMapping("/{id}")
    public JsonData deleteGoods(@PathVariable("id") long id) throws JSONException {

        try{
            int i = goodsService.deleteGoodsById(id);
        }catch(Exception e){

            return JsonData.buildError("删除失败");
        }


        return JsonData.buildSuccess("删除成功");
    }

    /**
     * 通过商品id批量删除商品
     * **/
    @PostMapping("/delMuti")
    public JsonData deleteGoodsMuti(@RequestParam(value = "idList") List<Long> idList) throws JSONException {
        int j = 0;
        //List<Long> idList1 = idList.getIdlist();
        try{
            for (int i = 0; i < idList.size(); i++) {
                j = goodsService.deleteGoodsById(idList.get(i));
            }
        }catch(Exception e){

            return JsonData.buildError("删除失败");
        }



        return JsonData.buildSuccess(j);
    }


    /**
     *修改商品信息
     * **/
    @PostMapping("/modifyInfo")
    public JsonData deleteGoods(GoodsAndPics goodsAndPics) throws JSONException {

        try{
            GoodsDetail goods = new GoodsDetail(goodsAndPics.getGoodId(), goodsAndPics.getTITLE(), goodsAndPics.getSUBTITLE(), goodsAndPics.getDETAIL(),
                    goodsAndPics.getPOINT(), goodsAndPics.getFirstPictureAddress(), goodsAndPics.getFirstDirectory(), goodsAndPics.getSecondDirectory(),
                    goodsAndPics.getClinkCount(), goodsAndPics.getClinkTime(), goodsAndPics.getListingTime(), goodsAndPics.getUpdateTime(), goodsAndPics.getGoodsStates(), goodsAndPics.getGoodsSort());


            int j = goodsService.modifyGoodsById(goods);

            List<String> pics = goodsAndPics.getPics();
            Long id = goodsAndPics.getGoodId();

            goodsService.modifyGoodsPicById(id, pics);

        }catch(Exception e){

            return JsonData.buildError("修改失败");

        }


        return JsonData.buildSuccess("修改成功");

    }

    /**
     * 根据商品id获得商品详细信息
     *
     * **/
    @GetMapping("/pass/get/{id}")
    public JsonData getGoodsById(@PathVariable("id") long id) throws JSONException {

        //JSONObject jsonObject = new JSONObject();
        List<DetailPicAdress> picAdresses = null;
        List<GoodsDetail> goods = null;
        GoodsDetail good = null;
        try{
            picAdresses = goodsService.getGoodsPicById(id);
            goods = goodsService.getGoodsById(id);
            good = goods.get(0);
        }catch(Exception e){
            return JsonData.buildError("查询失败");
        }


        List<String> adresses = new ArrayList<>();
        for (int i = 0; i < picAdresses.size(); i++) {
            adresses.add(picAdresses.get(i).getPictureAddress());
        }
        GoodsAndPics gp = new GoodsAndPics(good.getGoodId(), good.getTITLE(), good.getSUBTITLE(), good.getDETAIL(), good.getPOINT(),
                good.getFirstPictureAddress(), good.getFirstDirectory(), good.getSecondDirectory(), good.getClinkCount(), good.getClinkTime(),
                good.getListingTime(), good.getUpdateTime(), good.getGoodsStates(), good.getGoodsSort(), adresses);


        return JsonData.buildSuccess(gp);


    }

    /**置顶操作**/
//    @PostMapping("setTop")
//    public JSONObject setTop(@RequestParam("id") long id){
//        //查询多少已经置顶的商品
//
//        //如果大于等于2
//
//        //如果小于2
//    }

    /**
     * 按字段排序
     * **/
    @GetMapping("/order/pages")
    public JsonData getGoodsById(@RequestParam("page") int page,
                                   @RequestParam("limit") int limit, @RequestParam("keyWord") String keyWord,
                                   @RequestParam("col") String col, @RequestParam("status") int status) throws JSONException {


        List<GoodsDetail> goods = null;
        if(status==0){
            //JSONObject jsonObject1 = getGoodsPages(page, limit, keyWord);
            return getGoodsPages(page, limit, keyWord);
        }else if(status==1){ //正序
            goods = goodsDetailMapper.getOrderByColum((page-1)*limit, limit, keyWord, col);

        }else if(status==2){ //倒序
            goods = goodsDetailMapper.getOrderDescByColum((page-1)*limit, limit, keyWord, col);

        }else{

            return JsonData.buildError("查询失败");
        }

        return JsonData.buildSuccess(goods);
    }


    /**
     * 根据商品id置顶
     * **/
    @PostMapping("/setTop/{id}")
    public JsonData setById(@PathVariable("id") long id){
        try{
            List<String> res = goodsDetailMapper.selectTOP(id);
            String isTop = res.get(0);
            if(isTop.equals("0")){
                goodsDetailMapper.cancelTop(id);
            }else if(isTop.equals("1")){
                goodsDetailMapper.setTop(id);
            }
        }catch(Exception e){
            return JsonData.buildError("操作失败");
        }

        return JsonData.buildSuccess("置顶成功");

    }

    /**
     * 获取置顶商品
     * **/
    @GetMapping("/getTop")
    public JsonData getTop(){
        List<GoodsDetail> goods = null;
        try{
            goods = goodsDetailMapper.getTopGoods();
        }catch (Exception e){
            return JsonData.buildError("查询失败");
        }


        return JsonData.buildSuccess(goods);
    }

    /**
     * 上新推荐，4个产品
     * **/
    @GetMapping("/pass/getComment")
    public JsonData getConmment(int point, String device, int pv, String sex, String age){
        try{
            //在分数差值内随机取两个
            double pointMin = point * 0.8;
            double pointMax = point * 1.2;

            //置顶里面的两个
            List<GoodsDetail> goods2 = goodsDetailMapper.getTopGoods();
            //至少要找两个
            List<GoodsDetail> goods1 = goodsDetailMapper.getClosePoint(pointMin, pointMax);
            //凑到四个
            List<GoodsDetail> fourGoods = goodsDetailMapper.getFour();

            List<GoodsDetail> goods = new ArrayList<>();
            if(goods2.size() < 4){
                for (int i = 0; i < goods2.size(); i++) {
                    goods.add(goods2.get(i));
                }
                for(int i = 0; i < 4- goods2.size(); i++){
                    goods.add(fourGoods.get(i));
                }
                return JsonData.buildSuccess(goods);
            }else{
                return JsonData.buildSuccess(goods2);
            }
        }catch(Exception e){
            return JsonData.buildError("查询失败");
        }

        //return JsonData.buildSuccess(fourGoods);

    }

    /**
     * pv最高的10张
     * **/
    @GetMapping("/pass/getByPv")
    public JsonData getByPv(int number){

        List<GoodsDetail> goods;
        try{
            goods = goodsDetailMapper.getByPv(number);
        }catch (Exception e){
            return JsonData.buildError("查询失败");
        }

        return JsonData.buildSuccess(goods);
    }


    /**
     *随机取10条数据
     * **/
    @GetMapping("/pass/getByRandom")
    public JsonData getByRandom(int number){
        List<GoodsDetail> goods;
        try{
            goods = goodsDetailMapper.getByRandom(number);
        }catch (Exception e){
            return JsonData.buildError("查询失败");
        }

        return JsonData.buildSuccess(goods);
    }

    /**
     *根据id插入point（插入数据用）
     * **/
    @PostMapping("/InsertPoint")
    public JsonData InsertPointById(@RequestParam("id")Long goodsId,@RequestParam("count") int point){

        try{
            int i = goodsDetailMapper.addPoint(goodsId, point);
        }catch (Exception e){
            return JsonData.buildError("插入失败");
        }

        return JsonData.buildSuccess("插入成功");
    }




}

